 package cn.tcp;

import cn.Util.ByteQueue.ByteQueueUtil;
import cn.domain.Sensor;
import cn.domain.Tunnel;

import com.serotonin.messaging.WaitingRoomException;
import com.serotonin.modbus4j.exception.ModbusInitException;
import com.serotonin.modbus4j.exception.ModbusTransportException;
import com.serotonin.modbus4j.msg.ModbusRequest;
import com.serotonin.modbus4j.msg.ModbusResponse;
import com.serotonin.modbus4j.msg.MyReportSlaveIdRequest;
import com.serotonin.modbus4j.msg.MyWriteCoilRequest;
import com.serotonin.modbus4j.msg.ReadHoldingRegistersRequest;
import com.serotonin.util.queue.ByteQueue;

public class TcpNewUtil extends TcpSupport {

	public TcpNewUtil() {
		super("192.168.1.122");
	}

	/**
	 * 新方法可以可以不用写161，162，163， 对于开关id可以直接写 1，2，3
	 * 
	 * @param slaveId
	 *            节点ID
	 * @param switchID
	 *            开始偏移量 默认是冲161开始（a1）
	 * @param writeValue
	 *            打开 true 关闭false
	 */
	public boolean ControlSwitch(int slaveID, int switchID, boolean writeValue) {
		try {
			int tunnelLocation = switchID - 161;
			MyWriteCoilRequest modbusRequest = new MyWriteCoilRequest(slaveID,
					switchID, tunnelLocation, writeValue);

			int count = 0;
			while (true) {
				sendModbusRequest(modbusRequest);
				Thread.sleep(5000);
				Sensor sensor = GetSensorInformation(slaveID);
				Tunnel tunnel = sensor.getTunnels().get(tunnelLocation);
				if (tunnel.isOnoff() == writeValue) {
					break;
				} else {
					Thread.sleep(3000);
				System.out.println("开关状态未检测到，1.5S后重新发送开关请求。");
					count++;
					if (count > 3) {
						System.out.println("连续发送超时！");
						return false;
					}
				}
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 
	 * @param slaveId
	 *            节点ID
	 * @param switchID
	 *            开始偏移量 默认是冲161开始（a1）
	 * @param writeValue
	 *            打开 true 关闭false
	 */
	@Deprecated
	public void ControlSwitchOld(int slaveID, int switchID, boolean writeValue) {
		try {
			int tunnelLocation = switchID - 161;
			MyWriteCoilRequest modbusRequest = new MyWriteCoilRequest(slaveID,
					switchID, tunnelLocation, writeValue);
			sendModbusRequest(modbusRequest);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	/**
	 * 根据设备ID读取到传感器的信息
	 * 
	 * @param deviceId
	 *            设备ID
	 * @return 返回传感器对象
	 */
	public Sensor GetSensorInformation(int deviceId) {
		Sensor sensor = null;
		try {
			ipParameters.setEncapsulated(false);
			ModbusRequest modbusRequest = new ReadHoldingRegistersRequest(
					deviceId, 0, 20);
			ModbusResponse response = sendModbusRequest(modbusRequest);
			if (response != null) {
				ByteQueue queue = new ByteQueue();
				response.write(queue);
				sensor = ByteQueueUtil.ByteQueueToSensor(queue.toString());
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sensor;
	}


	public Tunnel getTunnelInformation() {
		try {
			Tunnel tunnel = new Tunnel();
			ipParameters.setEncapsulated(false);
			ModbusRequest modbusRequest = new MyReportSlaveIdRequest(40);
			ModbusResponse response = sendModbusRequest(modbusRequest);
			if (response != null) {
				ByteQueue queue = new ByteQueue();
				response.write(queue);
				System.out.println(queue);
			}
		} catch (ModbusTransportException e) {
			e.printStackTrace();
		}
		return null;
	}

	public void Test() {

	}

	/**
	 * 
	 * @param args
	 * @throws WaitingRoomException
	 * @throws ModbusInitException
	 * @throws ModbusTransportException
	 * @throws InterruptedException
	 */
	public static void main(String[] args) throws WaitingRoomException,
			ModbusInitException, ModbusTransportException, InterruptedException {
		TcpNewUtil tnu = new TcpNewUtil();
		// 15,1,0,0,0,17,3,10,0,0,0,2,4,a1,40,ff,ff
		// 00,0,0,0,0,0b,3,10,0,0,0,2,4,a1,40,ff,ff
		// 15,1,0,0,0,17,3,10,0,0,0,2,4,a1,40,0,0
		// tnu.getTunnelInformation();
	//	System.out.println( tnu.GetSensorInformation(1));
		tnu.ControlSwitchOld(3, 161, false);
//		 Thread.sleep(5000);
//		 tnu.ControlSwitchOld(3, 162, false);
//		 Thread.sleep(5000);
//		 tnu.ControlSwitchOld(3, 163, false);
//		 Thread.sleep(5000);
//		 tnu.ControlSwitchOld(3, 164, false);
		// // TODO 方法没写好
		// tnu.getTunnelInformation();
		// if(tnu.ControlSwitch(3, 162, false)){
		// System.out.println("开关操作成功");
		// }else{
		// System.out.println("开关操作失败");
		// }
		// System.out.println("===============================================");
		// System.out.println(tnu.GetSensorInformation(1)+" aaa");
		// Thread.sleep(1000);
		// System.out.println(tnu.GetSensorInformation(2));
		// Thread.sleep(1000);
		// System.out.println(tnu.GetSensorInformation(3));
		// Thread.sleep(1000);
		// for (int i = 0; i < 3; i++) {
		// tnu.ControlSwitch(3, 161 + i, i, true);
		// }
		// tnu.ControlSwitch(3, 161, 0, true);
		// Thread.sleep(1000);
		// tnu.ControlSwitch(3, 162, 1, false);
		// Thread.sleep(1000);
		// tnu.ControlSwitch(3, 163, 2, false);
		// Thread.sleep(1000);
		// tnu.ControlSwitch(3, 162, true);
		// Thread.sleep(1000);
		// tnu.ControlOneSwitchByTask(3, 2);
		// System.out.println(tnu.GetSensorInformation(3));
	}

}
